package cn.chiship.framework.business.biz.content.controller;

import cn.chiship.framework.business.biz.content.enums.ContentStatusEnum;
import cn.chiship.framework.business.biz.content.pojo.dto.ContentSyncWxPubDto;
import cn.chiship.framework.common.annotation.SystemOptionAnnotation;
import cn.chiship.framework.common.enums.BusinessTypeEnum;
import cn.chiship.framework.upms.biz.system.service.UpmsCategoryDictService;
import cn.chiship.sdk.cache.vo.CacheUserVO;
import cn.chiship.sdk.core.util.http.RequestUtil;
import cn.chiship.sdk.framework.base.BaseService;
import cn.chiship.sdk.framework.base.BaseController;
import cn.chiship.sdk.core.base.BaseResult;
import cn.chiship.sdk.core.util.StringUtil;
import cn.chiship.sdk.core.base.constants.BaseConstants;
import cn.chiship.sdk.core.annotation.Authorization;

import javax.annotation.Resource;

import cn.chiship.framework.business.biz.content.service.ContentArticleService;
import cn.chiship.framework.business.biz.content.entity.ContentArticle;
import cn.chiship.framework.business.biz.content.entity.ContentArticleExample;
import cn.chiship.framework.business.biz.content.pojo.dto.ContentArticleDto;
import cn.chiship.sdk.framework.pojo.vo.PageVo;
import cn.chiship.sdk.framework.util.ServletUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.beans.BeanUtils;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 文章内容控制层 2024/10/19
 *
 * @author lijian
 */
@RestController
@RequestMapping("/contentArticle")
@Api(tags = "文章内容")
public class ContentArticleController extends BaseController<ContentArticle, ContentArticleExample> {

    private static final Logger LOGGER = LoggerFactory.getLogger(ContentArticleController.class);

    @Resource
    private ContentArticleService contentArticleService;

    @Resource
    private UpmsCategoryDictService upmsCategoryDictService;

    @Override
    public BaseService getService() {
        return contentArticleService;
    }

    @ApiOperation(value = "文章内容分页")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "当前页码", defaultValue = "1", dataTypeClass = Long.class,
                    paramType = "query"),
            @ApiImplicitParam(name = "limit", value = "每页条数", defaultValue = "10", dataTypeClass = Long.class,
                    paramType = "query"),
            @ApiImplicitParam(name = "sort", value = "排序方式", defaultValue = "-gmtModified",
                    dataTypeClass = String.class, paramType = "query"),
            @ApiImplicitParam(name = "categoryId", value = "内容分类", dataTypeClass = String.class, paramType = "query"),
            @ApiImplicitParam(name = "status", value = "内容状态", dataTypeClass = Byte.class, paramType = "query"),
            @ApiImplicitParam(name = "title", value = "标题", dataTypeClass = String.class, paramType = "query"),
            @ApiImplicitParam(name = "keywords", value = "关键字主键", dataTypeClass = String.class, paramType = "query"),
            @ApiImplicitParam(name = "author", value = "作者", dataTypeClass = String.class, paramType = "query"),
            @ApiImplicitParam(name = "startDate", value = "发布时间", dataTypeClass = Long.class, paramType = "query"),
            @ApiImplicitParam(name = "endDate", value = "发布结束时间", dataTypeClass = Long.class, paramType = "query")
    })
    @GetMapping(value = "/page")
    @Authorization
    public ResponseEntity<BaseResult> page(
            @RequestParam(required = false, defaultValue = "", value = "categoryId") String categoryId,
            @RequestParam(required = false, defaultValue = "", value = "status") Byte status,
            @RequestParam(required = false, defaultValue = "", value = "title") String title,
            @RequestParam(required = false, defaultValue = "", value = "keywords") String keywords,
            @RequestParam(required = false, defaultValue = "", value = "author") String author,
            @RequestParam(required = false, defaultValue = "", value = "startDate") Long startDate,
            @RequestParam(required = false, defaultValue = "", value = "endDate") Long endDate) {
        ContentArticleExample contentArticleExample = new ContentArticleExample();
        // 创造条件
        ContentArticleExample.Criteria contentArticleCriteria = contentArticleExample.createCriteria();
        contentArticleCriteria.andIsDeletedEqualTo(BaseConstants.NO);
        if (!StringUtil.isNullOrEmpty(categoryId)) {
            contentArticleCriteria.andCategoryIdEqualTo(categoryId);
        }
        if (!StringUtil.isNull(status)) {
            if (!Byte.valueOf("-1").equals(status)) {
                contentArticleCriteria.andStatusEqualTo(status);
            }
        }
        PageVo pageVo = super.page(contentArticleExample);
        pageVo.setRecords(contentArticleService.assembleData(pageVo.getRecords()));
        return super.responseEntity(BaseResult.ok(pageVo));
    }

    @ApiOperation(value = "文章内容分页")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "当前页码", defaultValue = "1", dataTypeClass = Long.class,
                    paramType = "query"),
            @ApiImplicitParam(name = "limit", value = "每页条数", defaultValue = "10", dataTypeClass = Long.class,
                    paramType = "query"),
            @ApiImplicitParam(name = "sort", value = "排序方式", defaultValue = "-gmtModified",
                    dataTypeClass = String.class, paramType = "query"),
            @ApiImplicitParam(name = "categoryId", value = "内容分类", dataTypeClass = String.class, paramType = "query"),
            @ApiImplicitParam(name = "treeNumber", value = "内容层级", dataTypeClass = String.class, paramType = "query"),
            @ApiImplicitParam(name = "status", value = "内容状态", dataTypeClass = Byte.class, paramType = "query"),
            @ApiImplicitParam(name = "title", value = "标题", dataTypeClass = String.class, paramType = "query"),
            @ApiImplicitParam(name = "keywords", value = "关键字主键", dataTypeClass = String.class, paramType = "query"),
            @ApiImplicitParam(name = "author", value = "作者", dataTypeClass = String.class, paramType = "query"),
            @ApiImplicitParam(name = "startDate", value = "发布时间", dataTypeClass = Long.class, paramType = "query"),
            @ApiImplicitParam(name = "endDate", value = "发布结束时间", dataTypeClass = Long.class, paramType = "query"),
            @ApiImplicitParam(name = "isDelete", value = "是否物理删除", dataTypeClass = Byte.class, paramType = "query"),})
    @GetMapping(value = "/pageV2")
    @Authorization
    public ResponseEntity<BaseResult> pageV2(HttpServletRequest request) {
        PageVo pageVo = ServletUtil.getPageVo();
        String sort = pageVo.getSort();
        Map<String, String> paramsMap = RequestUtil.getParameterMap(request);
        String status = paramsMap.get("status");
        if (!StringUtil.isNullOrEmpty(status)) {
            if ("-1".equals(status)) {
                paramsMap.put("status", null);
            }
        }
        paramsMap.put("sort", sort);
        return super.responseEntity(contentArticleService.page(pageVo, paramsMap));
    }

    @ApiOperation(value = "文章内容分页(用户展示专用)")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "当前页码", defaultValue = "1", dataTypeClass = Long.class,
                    paramType = "query"),
            @ApiImplicitParam(name = "limit", value = "每页条数", defaultValue = "10", dataTypeClass = Long.class,
                    paramType = "query"),
            @ApiImplicitParam(name = "sort", value = "排序方式", defaultValue = "-gmtModified",
                    dataTypeClass = String.class, paramType = "query"),
            @ApiImplicitParam(name = "treeNumber", value = "内容层级", dataTypeClass = String.class, paramType = "query"),
            @ApiImplicitParam(name = "title", value = "标题", dataTypeClass = String.class, paramType = "query"),
            @ApiImplicitParam(name = "keywords", value = "关键字主键", dataTypeClass = String.class, paramType = "query"),
            @ApiImplicitParam(name = "author", value = "作者", dataTypeClass = String.class, paramType = "query"),
            @ApiImplicitParam(name = "startDate", value = "发布时间", dataTypeClass = Long.class, paramType = "query"),
            @ApiImplicitParam(name = "endDate", value = "发布结束时间", dataTypeClass = Long.class, paramType = "query"),})
    @GetMapping(value = "/pageV3")
    public ResponseEntity<BaseResult> pageV3(HttpServletRequest request) {
        PageVo pageVo = ServletUtil.getPageVo();
        String sort = pageVo.getSort();
        Map<String, String> paramsMap = RequestUtil.getParameterMap(request);
        paramsMap.put("sort", sort);
        paramsMap.put("status", String.valueOf(ContentStatusEnum.CONTENT_STATUS_PUBLISHED.getStatus()));
        paramsMap.put("isDeleted", String.valueOf(BaseConstants.NO));
        return super.responseEntity(contentArticleService.page(pageVo, paramsMap));
    }

    @SystemOptionAnnotation(describe = "文章内容列表数据")
    @ApiOperation(value = "文章内容列表数据")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "keyword", value = "关键字", dataTypeClass = String.class, paramType = "query")
    })
    @GetMapping(value = "/list")
    public ResponseEntity<BaseResult> list(
            @RequestParam(required = false, defaultValue = "", value = "keyword") String keyword) {
        ContentArticleExample contentArticleExample = new ContentArticleExample();
        // 创造条件
        ContentArticleExample.Criteria contentArticleCriteria = contentArticleExample.createCriteria();
        contentArticleCriteria.andIsDeletedEqualTo(BaseConstants.NO);
        if (!StringUtil.isNullOrEmpty(keyword)) {
        }
        return super.responseEntity(BaseResult.ok(super.list(contentArticleExample)));
    }

    @ApiOperation(value = "文章预览")
    @ApiImplicitParams({@ApiImplicitParam(name = "id", value = "主键", dataTypeClass = String.class, paramType = "path",
            required = true)})
    @GetMapping(value = "/view/{id}")
    public ResponseEntity<BaseResult> view(HttpServletRequest request, @PathVariable("id") String id) {
        CacheUserVO cacheUserVO = null;
        try {
            cacheUserVO = getLoginUser();
        } catch (RuntimeException e) {
            System.out.println("捕获令牌失效错误，不让前端对这个错误处理");
        }
        return super.responseEntity(contentArticleService.view(request, id, cacheUserVO));
    }

    @SystemOptionAnnotation(option = BusinessTypeEnum.SYSTEM_OPTION_SAVE, describe = "保存文章内容")
    @ApiOperation(value = "保存文章内容")
    @PostMapping(value = "save")
    @Authorization
    public ResponseEntity<BaseResult> save(@RequestBody @Valid ContentArticleDto contentArticleDto) {
        ContentArticle contentArticle = new ContentArticle();
        BeanUtils.copyProperties(contentArticleDto, contentArticle);
        return super.responseEntity(super.save(contentArticle));
    }

    @SystemOptionAnnotation(option = BusinessTypeEnum.SYSTEM_OPTION_UPDATE, describe = "更新文章内容")
    @ApiOperation(value = "更新文章内容")
    @ApiImplicitParams({@ApiImplicitParam(name = "id", value = "主键", dataTypeClass = String.class, paramType = "path",
            required = true)})
    @PostMapping(value = "update/{id}")
    @Authorization
    public ResponseEntity<BaseResult> update(@PathVariable("id") String id,
                                             @RequestBody @Valid ContentArticleDto contentArticleDto) {
        ContentArticle contentArticle = new ContentArticle();
        BeanUtils.copyProperties(contentArticleDto, contentArticle);
        return super.responseEntity(super.update(id, contentArticle));
    }

    @SystemOptionAnnotation(option = BusinessTypeEnum.SYSTEM_OPTION_REMOVE, describe = "删除文章内容")
    @ApiOperation(value = "删除文章内容")
    @PostMapping(value = "remove")
    @Authorization
    public ResponseEntity<BaseResult> remove(@RequestBody @Valid List<String> ids) {
        ContentArticleExample contentArticleExample = new ContentArticleExample();
        contentArticleExample.createCriteria().andIdIn(ids);
        return super.responseEntity(super.remove(contentArticleExample));
    }

    @SystemOptionAnnotation(option = BusinessTypeEnum.SYSTEM_OPTION_REMOVE, describe = "文章发布")
    @ApiOperation(value = "文章发布")
    @PostMapping(value = "release")
    @Authorization
    public ResponseEntity<BaseResult> release(@RequestBody @Valid List<String> ids) {
        if (ids.isEmpty()) {
            return super.responseEntity(BaseResult.error("集合不能为空！"));
        }
        return super.responseEntity(
                contentArticleService.changeStatus(ids, ContentStatusEnum.CONTENT_STATUS_PUBLISHED));
    }

    @SystemOptionAnnotation(option = BusinessTypeEnum.SYSTEM_OPTION_REMOVE, describe = "文章撤销发布")
    @ApiOperation(value = "文章撤销发布")
    @PostMapping(value = "revokePublication")
    @Authorization
    public ResponseEntity<BaseResult> revokePublication(@RequestBody @Valid List<String> ids) {
        if (ids.isEmpty()) {
            return super.responseEntity(BaseResult.error("集合不能为空！"));
        }
        return super.responseEntity(contentArticleService.changeStatus(ids, ContentStatusEnum.CONTENT_STATUS_RELEASED));
    }

    @SystemOptionAnnotation(option = BusinessTypeEnum.SYSTEM_OPTION_REMOVE, describe = "文章从回收站恢复")
    @ApiOperation(value = "文章从回收站恢复")
    @PostMapping(value = "recovery")
    @Authorization
    public ResponseEntity<BaseResult> recovery(@RequestBody @Valid List<String> ids) {
        if (ids.isEmpty()) {
            return super.responseEntity(BaseResult.error("集合不能为空！"));
        }
        return super.responseEntity(contentArticleService.recovery(ids));
    }

    @ApiOperation(value = "文章同步至微信素材库")
    @PostMapping(value = "syncWxPub")
    @Authorization
    public ResponseEntity<BaseResult> syncWxPub(@RequestBody @Valid ContentSyncWxPubDto contentSyncWxPubDto) {
        return super.responseEntity(contentArticleService.syncWxPub(contentSyncWxPubDto));
    }

    @ApiOperation(value = "文章从微信素材库撤销")
    @PostMapping(value = "revokeWxPub")
    @Authorization
    public ResponseEntity<BaseResult> revokeWxPub(@RequestBody @Valid String id) {
        if (StringUtil.isNullOrEmpty(id)) {
            return super.responseEntity(BaseResult.error("主键不能为空！"));
        }
        return super.responseEntity(contentArticleService.revokeWxPub(id));
    }

    @SystemOptionAnnotation(option = BusinessTypeEnum.SYSTEM_OPTION_REMOVE, describe = "文章移入回收站")
    @ApiOperation(value = "文章移入回收站")
    @PostMapping(value = "moveRecycleBin")
    @Authorization
    public ResponseEntity<BaseResult> moveRecycleBin(@RequestBody @Valid List<String> ids) {
        if (ids.isEmpty()) {
            return super.responseEntity(BaseResult.error("集合不能为空！"));
        }
        return super.responseEntity(contentArticleService.moveRecycleBin(ids));
    }

    @SystemOptionAnnotation(option = BusinessTypeEnum.SYSTEM_OPTION_UPDATE, describe = "文章设置是否允许评论")
    @ApiOperation(value = "文章设置是否允许评论")
    @PostMapping(value = "setAllowComment/{id}")
    @Authorization
    public ResponseEntity<BaseResult> setAllowComment(@PathVariable("id") String id,
                                                      @RequestBody @Valid Boolean allow) {
        return super.responseEntity(contentArticleService.setAllowComment(id, allow));
    }

    @ApiOperation(value = "时间维度统计文章数量")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "dateTime", value = "时间戳", dataTypeClass = Long.class, paramType = "query"),})
    @GetMapping(value = "analysisByTime")
    @Authorization
    public ResponseEntity<BaseResult> analysisByTime(@RequestParam(value = "dateTime") Long dateTime) {
        return super.responseEntity(contentArticleService.analysisByTime(dateTime));
    }

    @ApiOperation(value = "加载上一篇及下一篇")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "文章ID", required = true, dataTypeClass = String.class, paramType = "query"),
            @ApiImplicitParam(name = "categoryId", value = "频道（all或空：所有栏目）", dataTypeClass = String.class, paramType = "query"),
            @ApiImplicitParam(name = "isAll", value = "是否加载所有）", dataTypeClass = Boolean.class, paramType = "query"),
    })
    @GetMapping(value = "findPreAndNext")
    public ResponseEntity<BaseResult> findPreAndNext(@RequestParam(value = "id") String id,
                                                     @RequestParam(value = "isAll", required = false) Boolean isAll,
                                                     @RequestParam(value = "categoryId", required = false) String categoryId) {
        return super.responseEntity(contentArticleService.findPreAndNext(id, categoryId, isAll));
    }

}